package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 1-97-1 仓储服务-API-仓库管理-合并采购需求
     * 查询未领取的采购单
     */
    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        //查询出1,0的数据为status, 0 为新建, 1 为已分配未领取
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 1-97-1 仓储服务-API-仓库管理-合并采购需求
     * 合并采购需求, 如果采购单不存在, 就新建一个, 如果存在就合并到存在的
     *
     * @param mergeVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        // 获取采购单的id
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId==null){
            // 如果没有purchaseId, 则是自动创建一个采购单
            PurchaseEntity purchaseEntity=new PurchaseEntity();
            // 采购单状态设置为 0 新建
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // TODO 采购单存在, 要确认采购单状态是 0 或者 1 才可以合并

        // 接下来需要将采购需求 wms_purchase_detail合并到一个 采购单 wms_purchase 里去
        List<Long> items=mergeVo.getItems();
        Long finalPurchaseId=purchaseId;

        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseEntity = new PurchaseDetailEntity();
            // 采购需求的状态需要更改为已分配
            purchaseEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            purchaseEntity.setPurchaseId(finalPurchaseId);
            purchaseEntity.setId(i);
            return purchaseEntity;
        }).collect(Collectors.toList());
        // 批量修改采购需求的状态和所属的采购单
        purchaseDetailService.updateBatchById(collect);

        // 最后更新采购单的更新时间
        PurchaseEntity purchaseEntity=new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 1-98-1 仓储服务-API-仓库管理-领取采购单
     * 领取采购单, 这个接口应该是app调用的, 需要用postman测试
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void received(List<Long> ids) {
        // 1：确认当前采购单是新建或者已分配状态
        // 把采购单的详细信息查出来
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item->{
            // 过滤采购单, 需要是新建或者已分配状态
            if (item.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()||
                    item.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()  ){
                return true;
            }
            return false;
        }).map(items->{
            // 设置符合上面条件的采购单, 状态为已领取, 为后面更新做准备
            items.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            // 更新时间也设置上
            items.setUpdateTime(new Date());

            return items;
        }).collect(Collectors.toList());

        // 2：改变采购单的状态
        this.updateBatchById(purchaseEntities);

        //3：改变采购项(采购需求)的状态
        purchaseEntities.forEach((item->{
            // 查询采购单包含的采购需求
            List<PurchaseDetailEntity> entities= purchaseDetailService.listDetailByPurchaseId(item.getId());

            List<PurchaseDetailEntity> purchaseDetailEntities = entities.stream().map(entitiess -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entitiess.getId());
                // 更改采购需求为正在采购
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        }));
    }

    /**
     * 1-99-1 仓储服务-API-仓库管理-完成采购
     * 完成采购
     * 这个接口应该是app调用的, 需要用postman测试
     *
     * @param doneVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo doneVo) {
        // 采购单id
        Long id = doneVo.getId();

        //1、改变采购项的状态, 采购项都是成功的, 采购单的状态才能都是成功的
        // 否则, 采购单状态是 有异常的, 所以这里先走采购项的处理

        // 标志位, 采购单状态, 有一个采购项不成功, 采购单就不成功
        boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                // 采购项状态为失败
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else{
                // 采购项状态为成功
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 2、将成功采购的进行入库
                // 查出当前采购项的详细信息
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }

        // 更新采购项
        purchaseDetailService.updateBatchById(updates);

        // 3、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}